import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:ls_work/a_yyt/models/floor_list_entity.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/widgets/function_grid_widget.dart';

import '../res/colors.dart';
import '../res/styles.dart';
import '../viewmodel/select_old_view_model.dart';
import '../widgets/drop_item_widget.dart';
import '../widgets/load_image.dart';

class SelectOldPage extends BaseStatefulMvvmWidget {
  Function(MedicalElderInfo old) selectListener;

  final bool isMeal;
  final bool useLastFilter;
  SelectOldPage(this.selectListener,{this.isMeal = false,this.useLastFilter = false});

  @override
  State<StatefulWidget> createState() => _SelectOldState();
}

class _SelectOldState
    extends BaseMvvmRefreshState<SelectOldViewModel, SelectOldPage> {
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  GlobalKey _stackKey = GlobalKey();

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text("选择长者"),
        elevation: 0,
      ),
      body: Stack(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              GZXDropDownHeader(
                // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                items: [
                  GZXDropDownHeaderItem(
                      viewModel.selectBuilding?.buildingNo ?? "全部"),
                  GZXDropDownHeaderItem(viewModel.selectFloor?.floorNo ?? "全部"),
                ],
                // GZXDropDownHeader对应第一父级Stack的key
                stackKey: _stackKey,
                // controller用于控制menu的显示或隐藏
                controller: _dropdownMenuController,
                height: 50,
                color: Colors.white,
                borderColor: Colors.white,
                dividerColor: Colors.white,

                style: TextStyle(color: Colors.black, fontSize: 16),
                dropDownStyle: TextStyle(
                  fontSize: 16,
                  color: Colours.app_main,
                ),
                iconSize: 22,
                iconColor: Colors.black,
              ).addToContainer(color: Colors.white),
              Container(
                color: Colours.bg_color,
                child: Row(
                  children: [
                    CommonInput(
                      hintText: "请输入房间号/姓名",
                      border: InputBorder.none,
                      isDense: true,
                      padding: EdgeInsets.zero,
                      textInputAction: TextInputAction.search,
                      onChanged: (str) {
                        viewModel.searchName = str;
                      },
                      needClear: false,
                      onSubmitted: (str) {
                        viewModel.requestRefresh();
                      },
                    ).setWeight(1),
                    Image.asset("assets/icon_search.png",width: 16,height: 16,).onTap(() {
                      viewModel.requestRefresh();
                    })
                  ],
                ).addToContainer(
                    margin: EdgeInsets.symmetric(horizontal: 16, vertical: 9),
                    decoration: BoxDecoration(
                        color: Colors.white, borderRadius: 30.borderRadius),
                    padding:
                        EdgeInsets.symmetric(horizontal: 10, vertical: 10)),
              ),
              loadingContentWidget.setWeight(1)
            ],
          ),

          // 下拉菜单
          GZXDropDownMenu(
            // controller用于控制menu的显示或隐藏
            controller: _dropdownMenuController,
            // 下拉菜单显示或隐藏动画时长
            animationMilliseconds: 300,
            dropdownMenuChanging: (isShow, index) {},
            dropdownMenuChanged: (isShow, index) {},
            menus: [
              if((viewModel.buildingList??[]).isNotEmpty)
              GZXDropdownMenuBuilder(
                dropDownHeight: min(40.0 * (viewModel.buildingList??[]).length,
                    MediaQuery.of(context).size.height * 0.75),
                dropDownWidget:
                    buildConditionListWidget(viewModel.buildingList??[], (data) {
                  _dropdownMenuController.hide();
                  setState(() {
                    viewModel.selectBuilding = data as FloorEntity?;
                    viewModel.setFloor();
                    if(widget.useLastFilter){
                      GlobalConfigs.saveBuildingId(data.iId);
                      GlobalConfigs.saveFloorId(viewModel.selectFloor?.id?.toString()??"");
                    }
                  });
                  viewModel.requestRefresh();
                }),
              ),
              if((viewModel.floorList??[]).isNotEmpty)
              GZXDropdownMenuBuilder(
                dropDownHeight: min(40.0 * (viewModel.floorList??[]).length,
                    MediaQuery.of(context).size.height * 0.75),
                dropDownWidget:
                    buildConditionListWidget(viewModel.floorList??[], (value) {
                  _dropdownMenuController.hide();
                  setState(() {
                    viewModel.selectFloor = value as FloorInfo?;
                    if(widget.useLastFilter){
                      GlobalConfigs.saveFloorId(viewModel.selectFloor?.id?.toString()??"");
                    }
                  });
                  viewModel.requestRefresh();
                }),
              ),
            ],
          ),
        ],
        key: _stackKey,
      ),
    );
  }

  @override
  Widget createScrollWidget() {
    var ori = MediaQuery.of(context).orientation;
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: FunctionGridColumn(children: viewModel.listItems.map((item){
        return newOldContent(item).onTap(() {
          widget.selectListener(item);
        });
      }).toList(), count: ori==Orientation.portrait?3:6,crossSpace: 10,mainSpace: 10,),
    );
    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: ori==Orientation.portrait?3:6,
        childAspectRatio: 0.82,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 10.0,
      ),
      itemBuilder: (context, index) {
        var item = viewModel.listItems[index];
        return newOldContent(item).onTap(() {
          widget.selectListener(item);
        });
      },
      itemCount: viewModel.listItems.length,
    );
  }

  @override
  SelectOldViewModel createViewModel() {
    return SelectOldViewModel(context,isMeal: widget.isMeal,selectListener: widget.selectListener,useLastFilter: widget.useLastFilter);
  }

  @override
  bool get canPullUp => true;
}

Widget newOldContent(MedicalElderInfo item){
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    mainAxisSize: MainAxisSize.min,
    children: [
      Row(
        children: [
          Image.asset((item.sexName??"").contains('男') ? 'assets/icon_old_male.png' : 'assets/icon_old_female.png',width: 24,height: 23,),
          SizedBox(width: 4,),
          Text(item.name??"",style: TextStyle(fontSize: 16),).setWeight(1),
        ],
      ),
      SizedBox(height: 8,),
      Text(
        '${item.age ?? ""}岁',
        style: TextStyles.textGray14,
      ),
      SizedBox(height: 6,),
      Text(
        '${item.floorNo}#${item.roomNo}',
        style: TextStyles.textGray14,
      ),
      SizedBox(height: 6,),
      Text(
        item.nurseLevelName != null ? '${item.nurseLevelName}' : "",
        style: TextStyles.textGray14,
      ),
      SizedBox(height: 12,)
    ],
  ).addToContainer(
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: 4.borderRadius
    ),
    padding: EdgeInsets.only(left: 8,right: 8,top: 10)
  );
}

Widget oldContent(MedicalElderInfo item) {
  return Container(
    padding: EdgeInsets.all(3.0),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(8),
    ),
    child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '${item.name}',
              style: TextStyles.textDark16,
            ),
            LoadAssetImage(
              (item.sexName??"").contains('男') ? 'elder/e_man' : 'elder/e_weman',
            ),
          ],
        ),
        // Gaps.vGap5,
        Text(
          '${item.age ?? ""}岁',
          style: TextStyles.textGray14,
        ),
        // Expanded(
        //   child: Gaps.vGap5,
        // ),
        Text(
          '${item.floorNo}#${item.roomNo}',
          style: TextStyles.textNormal16,
        ),
        // Gaps.vGap5,
        Text(
          item.nurseLevelName != null ? '${item.nurseLevelName}' : "",
          style: TextStyles.textNormal16,
        ),
      ],
    ),
  );
}
